import Vue from 'vue'
import Vuex from 'vuex'
import api from "@/api/api"
import {
	ACCESS_TOKEN,
	USER_NAME,
	USER_INFO
} from "@/common/util/constants"

Vue.use(Vuex)

export default new Vuex.Store({
	state: {
		token: ``,
		userid: '',
		username: '',
		realname: '',
		welcome: '',
		avatar: ''
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = ``
		},
		SET_NAME: (state, {
			username,
			realname,
			welcome
		}) => {
			state.username = username
			state.realname = realname
			state.welcome = welcome
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
		}
	},
	actions: {
		// 登录
		passwordLogin({
			commit
		}, userInfo) {
			return new Promise((resolve, reject) => {
				uni.setStorageSync(ACCESS_TOKEN,"")
				api.passwordLogin(userInfo).then(response => {
					if (response.data.data.token) {
						uni.setStorageSync(ACCESS_TOKEN, JSON.stringify(response.data.data.token));
						console.log("缓存token",response.data.data)
						resolve(response)
					} else {
						resolve(response)
					}
				}).catch(error => {
					console.log("catch===>response", error)
					reject(error)
				})
			})
		},
		//手机号登录
		PhoneLogin({commit},userInfo) {
			return new Promise((resolve, reject) => {
				console.log('调用api' + userInfo)
				api.mylogin(userInfo)
				.then(response => {
					// if(response.data.data.toRegister){

					// }else{
					// 	let token = response.data.data
					// 	uni.setStorageSync(ACCESS_TOKEN,JSON.stringify(token))
					// }
					let token = response.data.data
					console.log('登录存token')
					uni.setStorageSync(ACCESS_TOKEN,JSON.stringify(token))
					resolve(response)
				}).catch(error => {
					reject(error)
				})
			})
		},
		//微信登录
		WxLogin({commit},userInfo) {
			return new Promise((resolve, reject) => {
				console.log('调用api' , userInfo)
				api.wxLogin(userInfo)
				.then(res => {
					if(res.data.data.toRegister){
						resolve(res)
					}else{
						uni.setStorageSync(ACCESS_TOKEN, JSON.stringify(res.data.data.token));
						resolve(res)
					}
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 登出
		Logout({
			commit,
			state
		}) {
			return new Promise((resolve) => {
				let logoutToken = state.token;
				commit('SET_TOKEN', '')
				uni.removeStorageSync(ACCESS_TOKEN)
				api.logout(logoutToken).then(() => {
					resolve()
				}).catch(() => {
					resolve()
				})
			})
		},

	},
	getters: {
		token: state => state.token,
		username: state => {
			state.userid = uni.getStorageSync(USER_INFO).username;
			return state.username
		},
		nickname: state => {
			state.userid = uni.getStorageSync(USER_INFO).realname;
			return state.user.realname
		},
		avatar: state => {
			state.userid = uni.getStorageSync(USER_INFO).avatar;
			return state.user.avatar
		},
		userid: state => {
			state.userid = uni.getStorageSync(USER_INFO).id;
			return state.userid
		},
	}
})
